//
//  LKDropPickerView.m
//  LKDropPickerView-Demo
//
//  Created by LIUKUN-PC on 17/5/3.
//  Copyright © 2017年 liukun. All rights reserved.
//

#define SCREEN_BOUNDS [[UIScreen mainScreen] bounds]
#define SCREEN_WIDTH  [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height

#import "LKDropPickerView.h"
#import "ZXContentAutoFit.h"


@interface LKDropPickerCollectionViewCell : UICollectionViewCell

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UIImageView *imageView;

@property (nonatomic, assign) CGFloat lenght;

@end

@implementation LKDropPickerCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initSubviews];
    }
    return self;
}

- (void)initSubviews {
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.font = [UIFont systemFontOfSize:15];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:self.titleLabel];
    
    self.imageView = [[UIImageView alloc] init];
    [self.contentView addSubview:self.imageView];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGFloat width = CGRectGetWidth(self.contentView.frame);
    
    CGFloat height = CGRectGetHeight(self.contentView.frame);
    
    self.imageView.frame = CGRectMake((width - self.lenght) / 2, 5, self.lenght, self.lenght);
    
    self.titleLabel.frame = CGRectMake(5, CGRectGetMaxY(self.imageView.frame) + 5, width - 10, height - CGRectGetMaxY(self.imageView.frame) - 10);
    
}


@end


@interface LKDropPickerView () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UIWindow *window;

@property (nonatomic, strong) UIView *bgView;

@property (nonatomic, strong) UIView *bottomView;

@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) UIView *topView;

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, assign) BOOL display;

/** 选择的index */
@property (nonatomic, assign) NSInteger selectedIndex;

@end

@implementation LKDropPickerView

#pragma mark - API

- (void)show {
    
    self.display = YES;
    
    self.userInteractionEnabled = NO;
    [self setupSubviews];
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.alpha = 1;
        
        CGRect frame = self.contentView.frame;
        frame.origin.y = 0;
        self.contentView.frame = frame;
        
        
        if (self.showBlock) {
            self.showBlock();
        }
        
    } completion:^(BOOL finished) {
        self.userInteractionEnabled = YES;
    }];
}

- (void)dismiss:(void(^)())completion {
    self.userInteractionEnabled = NO;
    
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.alpha = 0;
        CGRect frame = self.contentView.frame;
        frame.origin.y = - (self.imageLength + 35) * ceil(self.titles.count * 1.0 / self.maxCountAtSingleLine) - 20;
        self.contentView.frame = frame;
        
        
        if (self.dismissBlock) {
            self.dismissBlock();
        }
        
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        self.window.hidden = YES;
        self.userInteractionEnabled = YES;
        self.display = NO;
        self.window = nil;
        if (completion) {
            completion();
        }
        
    }];
}


#pragma mark - Init Methods

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initDatas];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        [self initDatas];
    }
    return self;
}

- (instancetype)init {
    if (self = [super init]) {
        [self initDatas];
    }
    return self;
}

- (void)initDatas {
    
    self.yOffset = 64;
    self.imageLength = 40;
    self.maxCountAtSingleLine = 4;
    
    
    self.frame = SCREEN_BOUNDS;
    self.backgroundColor = [UIColor clearColor];
    
}

- (void)setupSubviews {
    
    self.selectedIndex = 0;
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    CGFloat collectionViewHeight = (self.imageLength + 35) * ceil(self.titles.count * 1.0 / self.maxCountAtSingleLine);
    
    self.bgView = [[UIView alloc]initWithFrame:CGRectMake(0, self.yOffset, SCREEN_WIDTH, SCREEN_HEIGHT)];
    //超出视图的部分不显示
    self.bgView.clipsToBounds = YES;
    self.bgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    [self addSubview:self.bgView];
    
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, collectionViewHeight + 20, SCREEN_WIDTH, SCREEN_HEIGHT - collectionViewHeight + 20 - self.yOffset)];
    self.bottomView.backgroundColor = [UIColor clearColor];
    
    [self.bgView addSubview:self.bottomView];
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAction:)];
    [self.bottomView addGestureRecognizer:tapGR];
    
    
    self.contentView = [[UIView alloc] initWithFrame:CGRectMake(0, -collectionViewHeight - 20, SCREEN_WIDTH, collectionViewHeight + 20)];
    
    self.contentView.backgroundColor = [UIColor whiteColor];
    [self.bgView addSubview:self.contentView];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, collectionViewHeight) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.scrollEnabled = NO;
    self.collectionView.bounces = NO;
    [self.collectionView registerClass:[LKDropPickerCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([LKDropPickerCollectionViewCell class])];
    [self.contentView addSubview:self.collectionView];
    
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.yOffset)];
    self.topView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.topView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAction:)];
    [self.topView addGestureRecognizer:tap];
    
    self.window.hidden = NO;
    [self.window addSubview:self];
}

#pragma mark - Actions

- (void)dismissAction:(UITapGestureRecognizer *)tapGR {
    
    [self dismiss:nil];
}

#pragma mark - Collection View Delegete Flowlayout & Data Source

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.titles.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    LKDropPickerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LKDropPickerCollectionViewCell class]) forIndexPath:indexPath];
    
    cell.lenght = self.imageLength;
    cell.titleLabel.text = self.titles[indexPath.row];
    if (indexPath.row < self.imageNames.count) {
        cell.imageView.image = [UIImage imageNamed:self.imageNames[indexPath.row]];
    }
    
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(SCREEN_WIDTH / MIN(self.maxCountAtSingleLine, self.titles.count), self.imageLength + 35);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    self.selectedIndex = indexPath.item;
    [self dismiss:^{
        if (weakSelf.didClickedItemBlock) {
            weakSelf.didClickedItemBlock(indexPath.item);
        }
    }];
    
    
}





#pragma mark - Getter & Setter

- (UIWindow *)window {
    if (!_window) {
        _window = [[UIWindow alloc] initWithFrame:SCREEN_BOUNDS];
        _window.windowLevel = UIWindowLevelNormal;
        _window.backgroundColor = [UIColor clearColor];
        _window.rootViewController = [[UIViewController alloc] init];
        _window.hidden = NO;
    }
    return _window;
}

- (void)setImageLength:(CGFloat)imageLength {
    
    if (imageLength > SCREEN_WIDTH / MIN(self.titles.count, 4) - 20) {
        _imageLength = SCREEN_WIDTH / MIN(self.titles.count, 4) - 20;
    } else if (imageLength < 20) {
        _imageLength = 20;
    } else {
        _imageLength = imageLength;
    }
}


@end


static const CGFloat kImageLenght = 15;

@interface LKDropItem ()

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation LKDropItem

- (instancetype)initWithFrame:(CGRect)frame title:(NSString *)title {
    if (self = [self initWithFrame:frame]) {
        
        self.titleLabel.text = title;
    }
    return self;
}

- (CGFloat)fitWidth {
    return MIN([self.titleLabel.text widthWithMaxHeight:self.titleLabel.font.lineHeight + 5 font:self.titleLabel.font] + 4 + kImageLenght, self.maxWidth);
}

#pragma mark - Init Methods

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)init {
    if (self = [super init]) {
        [self initSubViews];
    }
    return self;
}

- (void)initSubViews {
    
     self.maxWidth = SCREEN_WIDTH - 130;
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    
    
    
    self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"lk_drop_picker_view"]];
    self.imageView.userInteractionEnabled = YES;
    [self addSubview:self.imageView];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.userInteractionEnabled = YES;
    [self addSubview:self.titleLabel];
    
    UITapGestureRecognizer *tapGR1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.imageView addGestureRecognizer:tapGR1];
    
    UITapGestureRecognizer *tapGR2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.titleLabel addGestureRecognizer:tapGR2];
    
}

- (void)layoutSubviews {
    [super layoutSubviews];

    CGFloat width = self.frame.size.width;
    
    CGFloat x = 0;
    
    switch (self.alignment) {
        case NSTextAlignmentCenter:
            x = (width - [self fitWidth]) / 2;
            break;
            
        case NSTextAlignmentRight:
            x = width - [self fitWidth];
            break;
        default:
            break;
    }

    self.titleLabel.frame = CGRectMake(x, 0, [self fitWidth] - 2 - kImageLenght, CGRectGetHeight(self.frame));
    
    self.imageView.frame = CGRectMake(CGRectGetMaxX(self.titleLabel.frame), (CGRectGetHeight(self.frame) - kImageLenght) / 2, kImageLenght, kImageLenght);
   
}

- (void)setAlignment:(NSTextAlignment)alignment {
    _alignment = alignment;
    [self layoutSubviews];
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
}


#pragma mark - Actions

- (void)tapAction:(UITapGestureRecognizer *)tapGR {
    if (self.tappedBlock) {
        self.tappedBlock();
    }
    
}




@end

@interface LKDropPickerItemView ()

@property (nonatomic, strong) LKDropPickerView *dropPickerView;

@property (nonatomic, strong) LKDropItem *item;

@end

@implementation LKDropPickerItemView

#pragma mark - API

- (instancetype)initWithframe:(CGRect)frame titles:(NSArray<NSString *> *)titles imageNames:(NSArray<NSString *> *)imageNames didClickedItemBlock:(void (^)(NSInteger index))didClickedItemBlock {
    if (self = [self initWithFrame:frame]) {
        self.dropPickerView.titles = titles;
        self.dropPickerView.imageNames = imageNames;
        
        __weak typeof(self) weakSelf = self;
        self.dropPickerView.didClickedItemBlock = ^(NSInteger index) {
            weakSelf.item.titleLabel.text = weakSelf.dropPickerView.titles[index];
            CGRect frame = weakSelf.frame;
            frame.size.width = [weakSelf.item fitWidth];
            weakSelf.frame = frame;
            
            [weakSelf.item layoutSubviews];
            
            if (didClickedItemBlock) {
                didClickedItemBlock(index);
            }
        };
        if (self.dropPickerView.selectedIndex < titles.count) {
            self.item.titleLabel.text = titles[self.dropPickerView.selectedIndex];
        }
        
    }
    return self;
}

#pragma mark - Init Methods

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)init {
    if (self = [super init]) {
        [self initSubViews];
    }
    return self;
}

- (void)initSubViews {
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    //此处init会调用InitWithFrame
    //(父视图的InitWithFrame方法中创建视图用init会调用子视图的InitWithFrame方法）
    self.item = [[LKDropItem alloc] init];
    self.item.alignment = NSTextAlignmentRight;
    
    
    [self addSubview:self.item];

    self.dropPickerView = [[LKDropPickerView alloc] init];
    
    __weak typeof(self) weakSelf = self;
    
    self.dropPickerView.showBlock = ^{
        weakSelf.item.imageView.transform = CGAffineTransformMakeRotation(M_PI);
    };
    
    self.dropPickerView.dismissBlock = ^{
        if (weakSelf.dropPickerView.selectedIndex < weakSelf.dropPickerView.titles.count) {
            weakSelf.item.titleLabel.text = weakSelf.dropPickerView.titles[weakSelf.dropPickerView.selectedIndex];
        }
        
        weakSelf.item.imageView.transform = CGAffineTransformMakeRotation(0);
    };
    
    self.item.tappedBlock = ^ {
        if (!weakSelf.dropPickerView.display) {
            [weakSelf.dropPickerView show];
        }
    };
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.item.frame = CGRectMake(0, 0, [self.item fitWidth], self.frame.size.height);
 

}


@end
